<template>
  <view class="waterfall-container">
    <view
      class="waterfall-column"
      v-for="(column, index) in columns"
      :key="index"
    >
      <ImageCard
        v-for="item in column"
        :key="item.id"
        :image="item"
        :lazy-load="true"
        @click="handleImageClick"
      />
    </view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import ImageCard from "../image-card/image-card.vue";
import { showInterstitialAd, shouldShowInterstitial } from "@/utils/ad-manager";
import { useImageStore } from "@/stores/image";

const props = defineProps({
  images: {
    type: Array,
    default: () => [],
  },
  columnCount: {
    type: Number,
    default: 2,
  },
});

const emit = defineEmits(["imageClick"]);

const imageStore = useImageStore();
const columns = ref([]);

// 初始化列数组
function initColumns() {
  columns.value = Array.from({ length: props.columnCount }, () => []);
}

// 分配图片到列（简单的轮询分配）
function distributeImages() {
  initColumns();
  props.images.forEach((image, index) => {
    const columnIndex = index % props.columnCount;
    columns.value[columnIndex].push(image);
  });
}

// 监听图片列表变化
watch(
  () => props.images,
  () => {
    distributeImages();
  },
  { immediate: true }
);

// 监听列数变化
watch(
  () => props.columnCount,
  () => {
    distributeImages();
  }
);

function handleImageClick(image) {
  emit("imageClick", image);

  // 检查是否需要显示插屏广告
  if (
    shouldShowInterstitial(
      imageStore.browseCount,
      imageStore.lastInterstitialTime
    )
  ) {
    showInterstitialAd();
    imageStore.resetBrowseCount();
  }
}

onMounted(() => {
  distributeImages();
});
</script>

<style scoped>
.waterfall-container {
  display: flex;
  padding: 20rpx;
  gap: 20rpx;
}

.waterfall-column {
  flex: 1;
  display: flex;
  flex-direction: column;
}
</style>
